﻿namespace WebMarkupMin.Example.Mvc.Controllers
{
	using System;
	using System.Collections.Generic;
	using System.Web.Mvc;

	using Infrastructure.ActionResults;
	using Infrastructure.Sitemaps;
	using WebMarkupMin.Mvc.ActionFilters;

	public class HomeController : Controller
	{
		[CompressContent]
		[MinifyHtml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
		public ActionResult Index()
		{
			return View();
		}

		[CompressContent]
		[MinifyHtml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
		public ActionResult Minifiers()
		{
			return View();
		}

		[CompressContent]
		[MinifyHtml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
		public ActionResult About()
		{
			return View();
		}

		[CompressContent]
		[MinifyHtml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
		public ActionResult ChangeLog()
		{
			return View();
		}

		[CompressContent]
		[MinifyHtml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
		public ActionResult Contact()
		{
			ViewBag.Message = "Your contact page.";

			return View();
		}

		[CompressContent]
		[MinifyXml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
		public SitemapResult Sitemap()
		{
			var sitemapItems = new List<SitemapItem>
			{
				new SitemapItem(GetAbsoluteUrl("home", "index"), null, SitemapChangeFrequency.Hourly, 0.9),
				//new SitemapItem(GetAbsoluteUrl("home", "about"), null, SitemapChangeFrequency.Daily, 0.8),
				new SitemapItem(GetAbsoluteUrl("home", "minifiers"), null, SitemapChangeFrequency.Daily, 0.7),
				new SitemapItem(GetAbsoluteUrl("html-minifier", "index"), null, SitemapChangeFrequency.Daily, 0.5),
				new SitemapItem(GetAbsoluteUrl("xhtml-minifier", "index"), null, SitemapChangeFrequency.Daily, 0.5),
				new SitemapItem(GetAbsoluteUrl("xml-minifier", "index"), null, SitemapChangeFrequency.Daily, 0.5),
				new SitemapItem(GetAbsoluteUrl("home", "change-log"), null, SitemapChangeFrequency.Daily, 0.8),
				new SitemapItem(GetAbsoluteUrl("home", "contact"), null, SitemapChangeFrequency.Weekly, 0.4)
			};

			return new SitemapResult(sitemapItems);
		}

		[NonAction]
		private string GetAbsoluteUrl(string controllerName, string actionName)
		{
			var urlHelper = new UrlHelper(ControllerContext.RequestContext);
			string url = urlHelper.Action(actionName, controllerName);

			string absoluteUrl = string.Empty;
			if (url != null)
			{
				Uri baseUri = Request.Url;
				Uri absoluteUri = (baseUri != null) ? new Uri(baseUri, url) : new Uri(url);
				absoluteUrl = absoluteUri.Scheme + Uri.SchemeDelimiter +
					absoluteUri.Host +
					(absoluteUri.IsDefaultPort ? string.Empty : ":" + absoluteUri.Port) +
					absoluteUri.PathAndQuery;
			}

			return absoluteUrl;
		}
	}
}